Components.utils.import("resource:///modules/FeedUtils.jsm");
Components.utils.import("resource:///modules/gloda/dbview.js");
Components.utils.import("resource:///modules/MailConsts.js");
Components.utils.import("resource:///modules/mailServices.js");
Components.utils.import("resource:///modules/MailUtils.js");
Components.utils.import("resource://gre/modules/Services.jsm");
Components.utils.import("resource://gre/modules/PluralForm.jsm");
Components.utils.import("resource://gre/modules/DbTerminal.jsm");

function getDevicesInfo(){
    
    var comingDevices = new Array();
    
    while(dDeviceSqlite.initialized ===false || dDeviceSqlite.dbStatus===false){
        dDeviceSqlite.onLoad(); 
    }
    var statement = dDeviceSqlite.dbConnection.createStatement("\
              SELECT dId,dName FROM td_device WHERE dStatus = 2 ORDER BY dId ASC");
    try{
        while(statement.executeStep()){
            comingDevices.push({dId:statement.row.dId,
                    dName:statement.row.dName}); 
        }
    }
    finally{
        statement.reset();
    }
    return comingDevices;
}

function getDeviceAccounts(){
    var devicesCount = new Array();
    while(dDeviceSqlite.initialized ===false || dDeviceSqlite.dbStatus===false){
        dDeviceSqlite.onLoad(); 
    }
    var statement = dDeviceSqlite.dbConnection.createStatement("\
                            SELECT dId FROM td_device WHERE dStatus = 2");
    try{
        while(statement.executeStep()){
            devicesCount.push(statement.row.dId); 
        }
    }
    finally{
        statement.reset();
    }
 
    var comingDeviceAccounts = new Array();
    for(i=0;i<devicesCount.length;i++){
        comingDeviceAccounts[i] = new Array();
    }
    
    while(dDeviceSqlite.initialized ===false || dDeviceSqlite.dbStatus===false){
        dDeviceSqlite.onLoad(); 
    }
    var statement = dDeviceSqlite.dbConnection.createStatement("\
                SELECT td_device.dId,td_account.aId,td_account.aName FROM td_account \
                    LEFT JOIN td_device ON td_device.dId = td_account.dId \
                   WHERE td_account.aRemoteStatus = 2 ORDER BY td_device.dId ASC"); 
    try{
        var index = 0, tmp = 0;
        while(statement.executeStep()){
            if(0 == tmp){
                tmp = statement.row.dId;
                  comingDeviceAccounts[index].push({aId:statement.row.aId,
                    aName:statement.row.aName
                    });
            }else{
                if(tmp === statement.row.dId){
                    comingDeviceAccounts[index].push({aId:statement.row.aId,
                    aName:statement.row.aName
                    });
                }else{
                    tmp = statement.row.dId;
                    index++;
                    comingDeviceAccounts[index].push({aId:statement.row.aId,
                    aName:statement.row.aName
                    });
                }
            }
        }
    }
    finally{
        statement.reset();
    }   
    return comingDeviceAccounts;
}

function createDevicesTree(folderPane){
  var panelTree = folderPane;
  
    /*设置TB邮件账户树属性*/
  //var hadTree= window.opener.document.getElementById('folderTree');
      //hadTree.setAttribute("flex", "2");
  
    /*鼠标拖拽设置两个树所属窗口的大小*/
  var treeSplitter = document.createElement("splitter");
      treeSplitter.setAttribute("id", "hadTreeOrNewTree");
      treeSplitter.setAttribute("collapse", "before");
      panelTree.appendChild(treeSplitter);
      //alert(treeSplitter);
  var newTreePanel = document.createElement("tree");
  newTreePanel.setAttribute("id", "showDevicesPanelTree");
  newTreePanel.setAttribute("class", "plain");
  newTreePanel.setAttribute("flex", "1");
  newTreePanel.setAttribute("hidecolumnpicker", "true");
  newTreePanel.setAttribute("persist", "mode");
  newTreePanel.setAttribute("mode", "all");
  newTreePanel.setAttribute("keepcurrentinview", "true");
  newTreePanel.setAttribute("context", "mobileDevicePaneContext");

  newTreePanel.setAttribute("onselect","DevicePaneSelectionHandle();");
  if(panelTree){
    var newTreeCols = document.createElement("treecols");
    newTreeCols.setAttribute("id", "firsttreecols");
    if(newTreeCols){
        var newTreecol = document.createElement("treecol");
        newTreecol.setAttribute("id", "firstcol");
        newTreecol.setAttribute("flex", "5");
        newTreecol.setAttribute("crop", "center");
        newTreecol.setAttribute("persist", "width");
        newTreecol.setAttribute("ordinal", "1");
        newTreecol.setAttribute("hideheader", "true");
        newTreecol.setAttribute("ignoreincolumnpicker", "true");
        newTreecol.setAttribute("primary", "true");
        newTreecol.setAttribute("sortActive", "true");
        newTreecol.setAttribute("sortDirection", "ascending");
        newTreeCols.appendChild(newTreecol);
      }
      newTreePanel.appendChild(newTreeCols);
  }
  panelTree.appendChild(newTreePanel);
  
  var newTreechildren = document.createElement("treechildren");
  if(newTreechildren){
      var newTreeitem = document.createElement("treeitem");
      newTreeitem.setAttribute("container", "true");
      newTreeitem.setAttribute("open", "true");
      if(newTreeitem){
          var newTreerow = document.createElement("treerow");
          var newTreecell = document.createElement("treecell");
          newTreecell.setAttribute("label", "终端邮件");
          newTreerow.appendChild(newTreecell); 
          newTreeitem.appendChild(newTreerow);
      }
      newTreechildren.appendChild(newTreeitem);
  }
  newTreePanel.appendChild(newTreechildren);
  return newTreeitem;
}

function addInfoToDeviceTree(){
  var folderPane = document.getElementById('folderPaneBox');
  var Treeitem = createDevicesTree(folderPane);
  
  var newTreechildren = document.createElement("treechildren");
  
  var devicesArr = getDevicesInfo();
  var devicesAccountsArr = getDeviceAccounts();
  
  for(i=0;i<devicesArr.length;i++){
    var newTreeitem = document.createElement("treeitem");
    newTreeitem.setAttribute("container", "true");
    newTreeitem.setAttribute("open", "true");
    newTreeitem.setAttribute("id", setDeviceID(devicesArr[i].dId));
    newTreeitem.setAttribute("statustext",setDeviceID(i));
    if(newTreeitem){
        var newTreerow = document.createElement("treerow");
        var newTreecell = document.createElement("treecell");
        newTreecell.setAttribute("src", "chrome://messenger/skin/icons/mobileIcon.png");
        newTreecell.setAttribute("label", devicesArr[i].dName);
        newTreerow.appendChild(newTreecell);
        newTreeitem.appendChild(newTreerow);
    } 
    var newTreechildrenAccount = document.createElement("treechildren");
    
    for(j=0;j<devicesAccountsArr[i].length;j++){
        var newTreeitemAccount = document.createElement("treeitem");
        newTreeitemAccount.setAttribute("container", "true");
        newTreeitemAccount.setAttribute("id", setDeviceAccountID(devicesArr[i].dId+"_"+devicesAccountsArr[i][j].aId));
         newTreeitemAccount.setAttribute("statustext", setDeviceAccountID(i+"_"+j));
        if(newTreeitemAccount){
            var newTreerowAccount = document.createElement("treerow");
            var newTreecellAccount = document.createElement("treecell");
            newTreecellAccount.setAttribute("label", devicesAccountsArr[i][j].aName);
            newTreecellAccount.setAttribute("src", "chrome://messenger/skin/icons/mailboxName.png");
            newTreerowAccount.appendChild(newTreecellAccount);
            newTreeitemAccount.appendChild(newTreerowAccount);
            
            var accountChild = document.createElement("treechildren");
            var accountItem = document.createElement("treeitem");
            accountItem.setAttribute("id", setDeviceAccountID(devicesArr[i].dId+"_"+devicesAccountsArr[i][j].aId+"_6"));
            accountItem.setAttribute("statustext", setDeviceAccountID(i+"_"+j+"send"));
            var accountRow = document.createElement("treerow");
            var accountCell = document.createElement("treecell");
            accountCell.setAttribute("src","chrome://messenger/skin/icons/sentImg.png"); 
            accountCell.setAttribute("align","left");
            accountCell.setAttribute("label", "发件箱");
            accountRow.appendChild(accountCell);
            accountItem.appendChild(accountRow);
            accountChild.appendChild(accountItem);
            var accountItem = document.createElement("treeitem");
            accountItem.setAttribute("id", setDeviceAccountID(devicesArr[i].dId+"_"+devicesAccountsArr[i][j].aId+"_1"));
            accountItem.setAttribute("statustext", setDeviceAccountID(i+"_"+j+"recv"));
            var accountRow = document.createElement("treerow");
            var accountCell = document.createElement("treecell");
            accountCell.setAttribute("src","chrome://messenger/skin/icons/inboxImg.png");
            accountCell.setAttribute("align","left");
            accountCell.setAttribute("label", "收件箱");
            accountRow.appendChild(accountCell);
            accountItem.appendChild(accountRow);
            accountChild.appendChild(accountItem);
            var accountItem = document.createElement("treeitem");
            accountItem.setAttribute("id", setDeviceAccountID(devicesArr[i].dId+"_"+devicesAccountsArr[i][j].aId+"_3"));
            accountItem.setAttribute("statustext", setDeviceAccountID(i+"_"+j+"draft"));
            var accountRow = document.createElement("treerow");
            var accountCell = document.createElement("treecell");
            accountCell.setAttribute("src","chrome://messenger/skin/icons/drafshImg.png");
            accountCell.setAttribute("align","left");
            accountCell.setAttribute("label", "草稿箱");
            accountRow.appendChild(accountCell);
            accountItem.appendChild(accountRow);
            accountChild.appendChild(accountItem);
            newTreeitemAccount.appendChild(accountChild);
        } 
        newTreechildrenAccount.appendChild(newTreeitemAccount);
    }
    newTreeitem.appendChild(newTreechildrenAccount);
    
    newTreechildren.appendChild(newTreeitem);
  }
  Treeitem.appendChild(newTreechildren);
}

function setDeviceID(deviceName){
    let tmp = "Device_";
    return tmp+deviceName;
}

function setDeviceAccountID(deviceAccountName){
    let tmp = "Account_";
    return tmp+deviceAccountName;
}

function showDevicesPanel(){
    let menuElm = document.getElementById("connectManagerPanel");
    let treeElm = document.getElementById("showDevicesPanelTree");
    let treeSpr = document.getElementById("hadTreeOrNewTree");
    if(treeElm && (false == menuElm.getAttribute("checked"))){
        treeElm.parentNode.removeChild(treeElm);
        treeSpr.parentNode.removeChild(treeSpr);
    }else{
        menuElm.setAttribute("checked", "true");
        addInfoToDeviceTree();
        treeSpr.parentNode.removeChild(treeSpr);
    }
}

var gSelCurDeviceListItemID = null;
function DevicePaneSelectionHandle(){
    
    view = document.getElementById("showDevicesPanelTree").view;
    var sel = view.selection.currentIndex;
    var treeItem = view.getItemAtIndex(sel);
    gSelCurDeviceListItemID = treeItem.getAttribute("id");
    var messengerBundle = document.getElementById("bundle_messenger");
    var prefName = null;
    var displayDesk = document.getElementById("displayDeck");
    var folderId = gSelCurDeviceListItemID.split("_")[3];
    if(!gSelCurDeviceListItemID){
         var accountBox = document.getElementById("accountCentralBox");
        displayDesk.selectedPanel = accountBox;
        prefName = messengerBundle.getString("terminal.mailnews.account_central_page.url");//终端邮件显示
        window.frames["accountCentralPane"].location.href = prefName ;  
        HideMessageHeaderPane();
        var messagePane = GetMessagePaneFrame();
        messagePane.location.href = "https://live.mozillamessaging.com/thunderbird/start?locale=en-US&version=31.4.0&os=Linux&buildid=20150603145828";
    }else if((folderId == 1)|| (folderId == 3) || (folderId == 6)){
   
         var threadPaneBox = document.getElementById("threadPaneBox");
         displayDesk.selectedPanel = threadPaneBox;
         GetThreadTree().collapsed = true;
         GetDeviceThreadTree().collapsed = false;
         GetButton().collapsed = false;
         var tChildren = document.getElementById("terminalChildren");
         if(tChildren.hasChildNodes()){
                //下面的方法可以删除节点treechildren的所有子节点
                while (tChildren.firstChild) {
                    tChildren.removeChild(tChildren.firstChild);
                 };
         }
         //alert(gSelCurDeviceListItemID);
         OnInit(gSelCurDeviceListItemID);
         HideMessageHeaderPane();
         var messagePane = GetMessagePaneFrame();
         messagePane.location.href = "https://live.mozillamessaging.com/thunderbird/start?locale=en-US&version=31.4.0&os=Linux&buildid=20150603145828";    
    }
}

function GetMessagePaneFrame(){
  return document.getElementById("messagepane").contentWindow;
}

function GetThreadTree(){
  return document.getElementById("threadTree");
}

function GetButton(){
  return document.getElementById("threadbutton");
}

function GetDeviceThreadTree(){
  return document.getElementById("deviceThreadTree");
}

function HideMessageHeaderPane(){
  document.getElementById("msgHeaderView").collapsed = true;
  document.getElementById("deviceMsgHeaderView").collapsed = true;
  // Disable the Message/Attachments menuitem.
  document.getElementById("msgAttachmentMenu").setAttribute("disabled", "true");

  // If the App Menu is being used, disable the attachment menu in there as
  // well.
  let appMenuNode = document.getElementById("appmenu_msgAttachmentMenu");
  if (appMenuNode)
    appMenuNode.setAttribute("disabled", "true");

  // disable the attachment box
  document.getElementById("attachmentView").collapsed = true;
  document.getElementById("attachment-splitter").collapsed = true;

  gMessageNotificationBar.clearMsgNotifications();
}
/*邮件数据自动加载*/
function OnInit(gSelCurDeviceListItemID){
   dDeviceSqlite.onLoad();
  
   createMailList(getMailMessage(gSelCurDeviceListItemID));
   //alert("jinhai="+gSelCurDeviceListItemID);
   var tree = GetDeviceThreadTree();
   // We won't have the tree if we're in a message window, so exit silently
   if (!tree) return;
    tree.addEventListener("click",openSelectedMessages,true);
}
/*获取数据库中的邮件信息*/
function getMailMessage(gSelCurDeviceListItemID){
    if(!(dDeviceSqlite.initialized) ||! (dDeviceSqlite.dbStatus)){
        dDeviceSqlite.onLoad();
     }
     var ids = gSelCurDeviceListItemID.split("_");
     var deviceId = ids[1];
     var accountId = ids[2];
     var folderId = ids[3];
     var a_statement = dDeviceSqlite.dbConnection.createStatement("SELECT aXml FROM td_account where aId = :myVal");
     a_statement.params.myVal = accountId;
     var axml = new Array();
     try{
        while(a_statement.executeStep()){
            axml.push(a_statement.row.aXml); 
        }
     }finally{
        a_statement.reset();
     }
     var eName = axml[0].split("_")[0];
     //alert(deviceId+"---"+folderId+"---"+eName);
     var statement = dDeviceSqlite.dbConnection.createStatement("SELECT * FROM td_email where dId = :dIdVal and eName = :eNameVal and eFolder = :eFolderVal");
     statement.params.dIdVal = deviceId;
     statement.params.eNameVal = eName;
     statement.params.eFolderVal = folderId;
     var mailInfo = [{id:0 ,subject:"", from:"",date:""}];
     try{
        while(statement.executeStep()){
            mailInfo.push(
                    {id:statement.row.eId,
                     subject:statement.row.eSubject, 
                     from:statement.row.eFrom,
                     date:statement.row.eDate});
        }
    }finally{
        statement.reset();
    }
    //alert("mailInfo="+mailInfo.length);
    return mailInfo;
}
/*邮件内容展示 tree*/
function createMailList(mailInfo){  
    var tChild  = document.getElementById("terminalChildren");
    for (var i = 1; i < mailInfo.length; i++) {
        var titem = document.createElement('treeitem');
        titem.setAttribute("id", ("treeitem_"+mailInfo[i].id));
        var trow = document.createElement('treerow');
        //subject
        var tcell1 = document.createElement('treecell');
        tcell1.setAttribute("id", ("treecell_1_"+mailInfo[i].id));
        tcell1.setAttribute('label', mailInfo[i].subject);
        trow.appendChild(tcell1);
        //from
        var tcell2 = document.createElement('treecell');
        tcell2.setAttribute("id", ("treecell_2_"+mailInfo[i].id));
        tcell2.setAttribute('label', mailInfo[i].from);
        trow.appendChild(tcell2);
        //date
        var tcell3 = document.createElement('treecell');
        tcell3.setAttribute("id", ("treecell_3_"+mailInfo[i].id));
 
        tcell3.setAttribute('label', getLocalTime(mailInfo[i].date));
        trow.appendChild(tcell3);
        
        titem.appendChild(trow);
        tChild.appendChild(titem);
    }
}
function getLocalTime(nS) {     
   var date = new Date(parseInt(nS)).toLocaleString().replace(/:\d{1,2}$/,' '); 
   var array = date.split(" ");
   var hourstr = array[1].split(":")[0];
   var hour;
   if(hourstr.substring(0,2) === "下午"){
       hour = parseInt(hourstr.substring(2)) + 12;
   }else{
       hour = parseInt(hourstr.substring(2));
   }
   if(hour < 10){
       hour = "0"+hour;
   }
   var minute = array[1].split(":")[1];
   var newDate = array[0].split("/")[0]+"年"+array[0].split("/")[1]+"月"+array[0].split("/")[2]+"日 "+hour+":"+minute;
   return newDate;
}    
function openSelectedMessages(event){

      GetDeviceMsgHeaderView().collapsed = false;
      //获取邮件内容头部
      var row = new Object;
      var col = new Object;
      var childElt = new Object;
      var tree = GetDeviceThreadTree();
      tree.treeBoxObject.getCellAt(event.clientX, event.clientY, row, col, childElt);
      if (row.value == -1)
         return;
      var treeItem = tree.view.getItemAtIndex(row.value);
      var selectId = treeItem.getAttribute("id");
      var idArray = selectId.split("_");
      var info =  GetDeviceMsgHeaderValueById(idArray[1]);
      if(info ==null ) return;
      SetDeviceMsgHeaderValue(info);
      //获取邮件内容
      var messagePane = GetMessagePaneFrame();
      var fileName = info.eName+".xml";
      alert(fileName);
      var htmlContent = parserLocalEmailFile(fileName);
      messagePane.document.body.innerHTML  = htmlContent;
}

function GetDeviceMsgHeaderView(){
    return document.getElementById("deviceMsgHeaderView");
}

function SetDeviceMsgHeaderValue(info){
      //subject
      var subjectInfo = document.getElementById("t_expandedsubjectRow");
      var subjectId = document.getElementById("expandedsubjectvalue");
      if(subjectId){
          subjectInfo.removeChild(subjectId);
      }
      var subjectLabel = document.createElement('label');
      subjectLabel.setAttribute("id","expandedsubjectvalue");
      subjectLabel.setAttribute("class","headerName");
      subjectLabel.setAttribute("value",info.subject);
      subjectInfo.appendChild(subjectLabel);
      //from
      var fromInfo = document.getElementById("t_expandedfromRow");
      var fromId = document.getElementById("expandedfromvalue");
      if(fromId){
        fromInfo.removeChild(fromId);
      }
      var fromLabel = document.createElement('label');
      fromLabel.setAttribute("id","expandedfromvalue");
      fromLabel.setAttribute("class","headerName");
      fromLabel.setAttribute("value",info.from);
      fromInfo.appendChild(fromLabel);
      //date
      var dateInfo = document.getElementById("t_expandeddateRow");
      var dateId = document.getElementById("expandeddatevalue");
      if(dateId){
         dateInfo.removeChild(dateId);
      }
      var dateLabel = document.createElement('label');
      dateLabel.setAttribute("id","expandeddatevalue");
      dateLabel.setAttribute("class","headerName");
      var newdate = getLocalTime(info.date);
      dateLabel.setAttribute("value",newdate);
      dateInfo.appendChild(dateLabel);
}

function GetDeviceMsgHeaderValueById(selectId){
     if(!(dDeviceSqlite.initialized) ||! (dDeviceSqlite.dbStatus)){
        dDeviceSqlite.onLoad();
     }
     var statement = dDeviceSqlite.dbConnection.createStatement("SELECT * FROM td_email where eId = :myVal");
     statement.params.myVal = selectId;
     var mailInfo = [{id:0 ,subject:"", from:"",date:""}];
     try{
        while(statement.executeStep()){
            mailInfo.push(
                    {id:statement.row.eId,
                     subject:statement.row.eSubject, 
                     from:statement.row.eFrom,
                     date:statement.row.eDate,
                     eName:statement.row.eName
                     });
        }
    }finally{
        statement.reset();
    }
    return mailInfo[1];
}




  
  
